package org.estela.util;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;

/**
 * Simple java logger formatter.
 *  
 * @version $Revision: 1.3 $
 * @author <a href="mailto:akantek@nyse.com">Antonio Kantek</a>
 */
public class SimpleFormatter extends java.util.logging.Formatter {

	private SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy hh:mm:ss");
	
	public static void installDefaultLogger() {
		InputStream xpheriaLog = SimpleFormatter.class.getResourceAsStream("log.properties");
		try {
			LogManager.getLogManager().readConfiguration(xpheriaLog);
			
		} catch (SecurityException ex) {
			throw new Error(ex);
		} catch (IOException ex) {
			throw new Error(ex);
		}
	}
	
	public String format(LogRecord record) {
		//StringBuilder builder = new StringBuilder();
		StringBuffer builder = new StringBuffer();
		builder.append(format.format(new Date(System.currentTimeMillis())));
		Level level = record.getLevel();
		builder.append(" ").append(record.getLevel()).append(" [");
		String className = record.getSourceClassName();
		int idx = className.lastIndexOf('.');
		if (level.intValue() > Level.CONFIG.intValue()) {
			if (idx != -1) {
				builder.append(className.substring(idx+1)).append(".").append(record.getSourceMethodName());
			} else {
				builder.append(className).append(".").append(record.getSourceMethodName());
			}
		} else {
			if (idx != -1) {
				builder.append(className.substring(idx+1)).append(".").append(record.getSourceMethodName());
			} else {
				builder.append(className).append(".").append(record.getSourceMethodName());
			}
		}
		builder.append("] ").append(record.getMessage()).append("\n");

		return builder.toString();
	}

}
